<?php

defined('IN_IA') or exit('Access Denied');
define('SERVERURL', 'http://iot.pouaka.com:20025');
define('bdkey', 'vittor_test_001_liuzhufeng_20180413184901');
class vittor_homework_cabinetModuleProcessor extends WeModuleProcessor {
    
    public static function postRequest($data='',$serverurl=SERVERURL,$content_type='text/plain') {
        $ch = curl_init($serverurl);
        if(is_array($data)){
            $postdata = http_build_query($data);
        }else{
            $postdata=$data;
        }
        //print_r($postdata);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:'.$content_type.';charset=utf-8'));
        $result=curl_exec($ch);
        curl_close($ch);
        return $result;
    }    
    public function post_open_door($device_info_id,$door=0){
		$request_data = array(
			'bdkey'=>bdkey,
			'platform'=>'opensource',
			'api'=>'opendevice',
            'device_info_id'=>$device_info_id,
            'door_num'=>$door
		);
        $data=json_decode($this->postRequest($request_data),true);
        //这里的数据返回后还需要处理
        return $data;
    }    
    
    public function respond(){
        $rolearray = array('admin','teacher','student');
        $data = '';
        $this->beginContext(5);
        // if($this->message['content']=='绑定36柜子3号门与教师1'){
            // $this->endContext();
            // return $this->respNews(array(
                                        // 'Title' => '绑定36柜子3号门与!',
                                        // 'Description' => '点我进入绑定页面!',
                                        // 'PicUrl'=>'http://pic8.nipic.com/20100617/2177138_161648562298_2.jpg',
                                        // 'Url' => $this->createMobileUrl('scangenerate', array('ac' => 'scan' , 'op' =>'door_student', 'info_id'=>'36' ,'door'=>'3','random'=>'pI03GDTBcH','device_name'=>urlencode('逸夫馆'))),
                                    // ));            
        // }
        if($this->message['msgtype'] === 'event'){
            if($this->message['event'] === 'SCAN' || $this->message['event'] === 'subscribe' )
            {     
                global $_W;
                $qrMessage = $this->message['content'];//扫描到的二维码信息
                $qrMessage=explode("#",$qrMessage);
                $qrMessage=explode('@',$qrMessage[1]);
                
                $current_model = $qrMessage[0];
                $info_id = $qrMessage[1];
                $openid = $this->message['from'];
                //判断openid的role
                //能否直接获取到$_W['uniacid']，$_W['openid']？在测试号都能
                $current_user = pdo_get('homework_user', array('uniacid' => $_W['uniacid'] ,'openid'=>$openid), array('id' ,'name' ,'role'));
                $role = $current_user['role'];
                if(!in_array($role , $rolearray)){
                    $this->endContext();
                    return $this->respText('您还为未与作业柜进行绑定');
                }
                if($role == $rolearray[0]){//role为管理员
                    return $this->respNews(array(
                                                'Title' => '管理员开柜!',
                                                'Description' => '点我进入管理员开柜页面!',
                                                'PicUrl'=>'http://pic8.nipic.com/20100617/2177138_161648562298_2.jpg',
                                                'Url' => $this->createMobileUrl('open', array('ac' => 'opendoor' , 'info_id'=>$info_id)),
                                            ));                    
                }
                if($role == $rolearray[1]){//role为教师
                    $getall = pdo_getall('homework_door_teacher', array('uniacid'=>$_W['uniacid'],'userid'=>$current_user['id'],'device_info_id'=>$info_id), array('door'));
                    if($getall == null|sizeof($getall)==0){
                        $this->endContext();
                        return $this->respText('您还为未与当前作业柜进行绑定');
                    }
                    if(sizeof($getall)===1){
                        $data = $this->post_open_door($info_id,$getall[0]['door']);
                        $this->endContext();
                        if($data['state']!='success')
                            return $this->respText($getall[0]['door'].'号门：开启失败');
                        else
                            return $this->respText($getall[0]['door'].'号门：开启成功');                       
                    }
                    if(sizeof($getall)>1){
                        return $this->respNews(array(
                                                    'Title' => '教师开柜!',
                                                    'Description' => '点我进入教师开柜页面!',
                                                    'PicUrl'=>'http://pic8.nipic.com/20100617/2177138_161648562298_2.jpg',
                                                    'Url' => $this->createMobileUrl('open', array('ac' => 'opendoor' , 'info_id'=>$info_id)),
                                                ));                        
                    }
                }
                if($role == $rolearray[2]){//role为学生
                    $getall = pdo_getall('homework_door_student', array('uniacid'=>$_W['uniacid'],'device_info_id'=>$info_id), array('userid','door'));
                    $count = 0;
                    foreach($getall as $key=>$value){
                        $temp = explode(',',$value['userid']);
                        if(in_array($current_user['id'],$temp)){
                            $getall_index = $key;
                            $count++;
                        } 
                    }
                    if($count==0){
                        $this->endContext();
                        return $this->respText('您还为未与当前作业柜进行绑定');
                    }
                    if($count==1){
                        $open_data = $this->post_open_door($info_id,$getall[$getall_index]['door']);
                        $this->endContext();
                        if($open_data['state']!='success'){
                            return $this->respText($getall[$getall_index]['door'].'号门：开启失败');
                        }else{
                            //需要发送模板消息给教师
                            $teacher_id = pdo_get('homework_door_teacher', array('uniacid'=>$_W['uniacid'],'device_info_id'=>$info_id,'door'=>$getall[$getall_index]['door']), array('userid'));
                            $teacher_openid = pdo_get('homework_user', array('uniacid' => $_W['uniacid'] ,'id'=>$teacher_id['userid']), array('openid','name'));
                            $device_name = pdo_get('homework_cabinet_admin', array('uniacid'=>$_W['uniacid'],'device_info_id'=>$info_id), array('device_name'));
                            
                            
                            $account_api = WeAccount::create();
                            $token = $account_api->getAccessToken();
                            if(is_error($token)){
                                return $this->respText($getall[$getall_index]['door'].'号门：开启成功。'.'但与该柜门绑定的教师没有收到通知，如有需要请自行微信通知老师');                           
                            }
                            $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;
                            $template_id = '4sT4hto1K27PMwQgodhSsgL_0cDCzrHYRJvd17dlUPg';
                            $templateData = array('first'=>array(
                                                            'value'=>'您的课代表'.$current_user['name'].'开启了柜门',
                                                            'color'=>'#173177'),
                                                    'info_fo'=>array(
                                                            'value'=>$info_id,
                                                            'color'=>'#173177'),
                                                    'device_name'=>array(
                                                            'value'=>$device_name['device_name'],
                                                            'color'=>'#173177'),
                                                    'door'=>array(
                                                            'value'=>$getall[$getall_index]['door'],
                                                            'color'=>'#173177'),
                                                    'name'=>array(
                                                            'value'=>$current_user['name'],
                                                            'color'=>'#FF0000'),
                                                    'remark'=>array(
                                                            'value'=>'请'.$teacher_openid['name'].'老师安排时间去作业柜取作业',
                                                            'color'=>'#173177'));
                            $data = array(
                                'touser'=>$teacher_openid['openid'],
                                'template_id'=>$template_id,
                                'data'=>$templateData
                            );
                            $re=json_decode($this->postRequest(json_encode($data) , $url),true);
                            if($re['errmsg']!='ok')
                                return $this->respText($getall[$getall_index]['door'].'号门：开启成功!'.'但与该柜门绑定的教师没有收到通知，如有需要请自行微信通知老师');
                            else
                                return $this->respText($getall[$getall_index]['door'].'号门：开启成功');                           
                        }      
                    }
                    if($count>1){
                        return $this->respNews(array(
                                                    'Title' => '课代表开柜!',
                                                    'Description' => '点我进入课代表开柜页面!',
                                                    'PicUrl'=>'http://pic8.nipic.com/20100617/2177138_161648562298_2.jpg',
                                                    'Url' => $this->createMobileUrl('open', array('ac' => 'opendoor' , 'info_id'=>$info_id)),
                                                ));
                    }
                }
               
            }
        }
        $this->endContext();
        //return $this->respText($_W['uniacid'].'fdsfa');
    
    }
    

}

